//促销管理
import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { Input, Select, Space, Button, Form, Table, DatePicker, Switch, Image, Modal, message, InputNumber, Collapse } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import { ConfigProvider } from 'antd';
import zh_CN from 'antd/es/locale/zh_CN';
import type { TableRowSelection } from 'antd/es/table/interface';
import { getPromotional, deletePromotional ,getCircuit,getRoute} from '../../../api/promotion';
import { number } from 'echarts';
import getSelectTime from '../../../utils/date'
import { values } from 'mobx';
const { RangePicker } = DatePicker;
//表格数据类型
interface DataType {
    id: number;//序号
    title: string;//名称
    detial: string;//详情
    type: string;//行程
    creat: string;//添加时间
    state: number;//上下架状态

}
export default function Promotionma() {
    const [ModalOpen, setModalOpen] = useState(false);//删除弹框
    const [isModalOpen, setIsModalOpen] = useState(false);//修改弹框
    const [amend, setAmend] = useState(Object);//装修改内容
    const [data, setData] = useState<DataType[]>();//装表格内容
    const [page, setPage] = useState(1)//页码
    const [pageSize, setPagesize] = useState(5)//一页几条
    const [date, setDate] = useState(String) //创建时间
    const [state, setState] = useState(number) //状态 1开启
    const [title, setTitle] = useState(String) //标题
    const [id, setID] = useState<number>() //id
    const [form] = Form.useForm()
    const { Panel } = Collapse;
    const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
    const [count,setCount] = useState<number>()
    //路由跳转
    const navigate = useNavigate()
    //表格部分
    const columns: ColumnsType<DataType> = [
        {
            title: '序号',
            dataIndex: 'id',
        },
        {
            title: '促销标题',
            dataIndex: 'title',
        },
        {
            title: '详情',
            dataIndex: 'detial',
        },
        {
            title: '行程',
            dataIndex: 'type',
        },
        {
            title: '是否上架',
            dataIndex: 'state',
            render: (_, record) => (
                <Switch defaultChecked={record.state === 1 ? true : false}
                    onChange={onChange}
                    onClick={()=>{labelChange(record)}} />
            ),
        },
        {
            title: '添加时间',
            dataIndex: 'creat',
        },
        {
            title: '操作',
            dataIndex: 'address',
            render: (_, record) => (
                <Space size="middle">
                    <Button className='reset' onClick={() =>Commodity(record)}>商品管理</Button>
                    <Button type="primary" className='edmit' onClick={() => edmit(record)} htmlType="submit">修改</Button>
                    <Button id='del' onClick={() => showModal(record)}>删除</Button>
                </Space >
            ),
        },
    ];
    const onSelectChange = (newSelectedRowKeys: React.Key[]) => {
        console.log('selectedRowKeys changed: ', newSelectedRowKeys);
        setSelectedRowKeys(newSelectedRowKeys);
    };

    const rowSelection: TableRowSelection<DataType> = {
        selectedRowKeys,
        onChange: onSelectChange,
        selections: [
            Table.SELECTION_ALL,
            Table.SELECTION_INVERT,
            Table.SELECTION_NONE,
            {
                key: 'odd',
                text: 'Select Odd Row',
                onSelect: (changableRowKeys) => {
                    let newSelectedRowKeys = [];
                    newSelectedRowKeys = changableRowKeys.filter((_, index) => {
                        if (index % 2 !== 0) {
                            return false;
                        }
                        return true;
                    });
                    setSelectedRowKeys(newSelectedRowKeys);
                },
            },
            {
                key: 'even',
                text: 'Select Even Row',
                onSelect: (changableRowKeys) => {
                    let newSelectedRowKeys = [];
                    newSelectedRowKeys = changableRowKeys.filter((_, index) => {
                        if (index % 2 !== 0) {
                            return true;
                        }
                        return false;
                    });
                    setSelectedRowKeys(newSelectedRowKeys);
                },
            },
        ],
    };

    //获取页码
    const Change = (page: number, pageSize: number) => {
        console.log(page, pageSize);
        setPage(page)
        setPagesize(pageSize)
    }

    useEffect(() => {
        getproducts()
    }, [page, pageSize])

    //获取促销商品内容
    const getproducts = () => {
        getPromotional({
            num: page,
            size: pageSize,
        }).then(res => {
            console.log('获取促销列表', res);
            if (res.code == '200') {
                setData(res.data.all)
                setCount(res.data.total)
            }
        }).catch(err => {
            console.log('失败', err);
        })


    }

    //上下架状态
    const OnChange  = (value:number) => {
        console.log(`selected`,value);
    }

    //时间状态
    const handleChange = (value: number) => {
        // console.log(`selected`,value);
        getPromotional({
            num: page,
            size: pageSize,
            sort:value
        }).then(res => {
            console.log('排序成功', res);
            if (res.code == '200') {
                setData(res.data.all)
                setCount(res.data.total)
            }
        }).catch(err => {
            console.log('排序失败', err);
        })
        message.success('排序成功！')

    };

    //查询获取input框内容
    const onFinish = (values: any) => {
        console.log('----------',values);
        const date = values.stateTime?getSelectTime(values.stateTime):values.stateTime
        getPromotional({
            num: page,
            size: pageSize,
            date,
            state:values.state,
            title:values.keyword
        }).then(res => {
            console.log('查询成功', res);
            if (res.code == '200') {
                setData(res.data.all)
                setCount(res.data.total)
            }
        }).catch(err => {
            console.log('查询失败', err);
        })
        message.success('查询成功！')
    }

    //重置
    const resetting = () => {
        getproducts()
        message.success('重置成功！')
    }

    //添加
    const add = () => {
        navigate('/home/promotion/AddPromotion')

    }

    //点击跳转商品管理
    const Commodity = (record:any) => {
        console.log('va',record);
        // navigate(`/home/promotion/commodity`)
        navigate('/home/promotion/commodity',{
            state:{
                id :record.id
            }
        })
    }

    useEffect(() => {
        form.setFieldsValue({
            title: amend.title,
            detial: amend.detial,
            type: amend.type,
            state: amend.state,
        })
        // console.log('gengg',amend);
    }, [amend])
    
    //修改
    const edmit = (record: any) => {
        setAmend(record)
        setIsModalOpen(true);
        console.log('修改', record);

    }

    const ehandleOk = () => {
        setIsModalOpen(false);
        message.success('修改成功！')
    };

    const ehandleCancel = () => {
        setIsModalOpen(false);
    };

    //删除
    const showModal = (record: any) => {
        setModalOpen(true);
        console.log('OK', record);
        setID(record.id)
    };

    const handleOk = () => {
        setModalOpen(false);
        deletePromotional({
            id:id
        }).then(res => {
            console.log('删除成功', res);
            if (res.code == '200') {
                getproducts()   
            }
        }).catch(err => {
            console.log('删除失败', err);
        })
        message.success('删除成功！')
    };

    const handleCancel = () => {
        setModalOpen(false);
    };

    //启动按钮
    const labelChange = (v:any) => {
        console.log('v',v);
        getCircuit({
            id:v.id
        }).then(res => {
            console.log('修改开关成功', res);
            if (res.code == '200') {
                getproducts()   
            }
        }).catch(err => {
            console.log('修改开关失败', err);
        })
        
    }
    //启动按钮
    const onChange = (record:any) => {
        console.log(`switch`,record);
    };
    return (
        <div>
            {/* 标题 */}
            <p className="head">促销管理</p>
            {/* 操作部分 */}
            <Collapse className='collapse' defaultActiveKey={['1']}>
                <Panel header="筛选查询" key="1">
                    <div className='operate-wrap'>
                        <div className='operate-left'>
                            <Form className='operate-left operate-left-item' onFinish={onFinish}>
                                <Form.Item label="关键词：" className='operate-left-item' name='keyword'>
                                    <Input placeholder="标题关键词" className='search' />
                                </Form.Item>
                                <Form.Item label='状态：' className='operate-left-item' name='state'>
                                    <Select
                                        onChange={OnChange}
                                        style={{ width: 120 }}
                                        allowClear
                                        options={[{ value: '0', label: '未上架' }, { value: '1', label: '已上架' }]}
                                        className='drop'
                                    />
                                </Form.Item>
                                <Form.Item label='上架时间：' className='operate-left-item' name='stateTime'>
                                    <DatePicker showTime />
                                </Form.Item>
                                <Form.Item>
                                    <Button className='inquire operate-left-item' htmlType='submit'>查询</Button>
                                    <Button className='reset operate-left-item' onClick={resetting} >重置</Button>
                                </Form.Item>
                            </Form>
                        </div>
                    </div>
                </Panel>
            </Collapse>
            <div className='table'>
                {/* 表格操作 */}
                <div className='operationTable'>
                    {/* 排序 */}
                    <Form>
                        <Form.Item label='排序：' className='operate-left-item' name='state'>
                            <Space wrap>
                                <Select
                                    onChange={handleChange}
                                    style={{ width: 120 }}
                                    allowClear
                                    options={[{ value: '2', label: '按时间倒序' }, { value: '1', label: '按时间顺序' }]}
                                    className='drop'
                                />
                            </Space>
                        </Form.Item>
                    </Form>
                    <Button id='del' className='operate-left-item'>批量删除</Button>
                    <Button className='add' onClick={add}>添加</Button>
                </div>
                {/* 表格 */}
                <ConfigProvider locale={zh_CN}>
                    <Table rowSelection={rowSelection} columns={columns} rowKey={item => item.id} dataSource={data} pagination={{
                        position: ['bottomRight'],
                        defaultPageSize: 5,
                        pageSizeOptions: [1, 5, 10, 15],
                        showQuickJumper: true,
                        showSizeChanger: true,
                        onChange: Change,
                        pageSize:pageSize,
                        total:count,
                    }} />
                </ConfigProvider>
            </div>
            {/* 删除内容 */}
            <Modal title="提示" open={ModalOpen} onOk={handleOk} onCancel={handleCancel} okText='确定' cancelText='取消'>
                <p>确定要删除该条数据吗？</p>
            </Modal>
            {/* 修改弹框 */}
            <Modal title="修改促销内容" open={isModalOpen} onOk={ehandleOk} onCancel={ehandleCancel} okText='确定' cancelText='取消'>
                <Form
                    labelCol={{ span: 7 }}
                    wrapperCol={{ span: 16 }}
                    layout="horizontal"
                    style={{ maxWidth: 600 }}
                    onFinish={onFinish}
                    autoComplete="off"
                    form={form}
                >
                    <Form.Item label="促销标题" name='title' rules={[{ required: true, message: '请输入促销标题' }]} initialValue={amend.title} >
                        <Input placeholder="请输入促销标题" />
                    </Form.Item>
                    <Form.Item label="详情" name='detial' rules={[{ required: true, message: '请输入详情' }]} initialValue={amend.detial}>
                        <Input placeholder="请输详情" />
                    </Form.Item>
                    <Form.Item label="适用行程类型" name='type' rules={[{ required: true, message: '请选择行程类型' }]} initialValue={amend.type}>
                        <Select>
                            <Select.Option value="demi">登山</Select.Option>
                            <Select.Option value="demo">骑车</Select.Option>
                        </Select>
                    </Form.Item>
                    <Form.Item label="上架" valuePropName="checked" name='state' initialValue={amend.state} >
                        <Switch />
                    </Form.Item>
                </Form>
            </Modal>
        </div>
    )
}
